package org.changchen.fgt.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.changchen.fgt.controller.LiveEpgDto;
import org.changchen.fgt.service.LiveEpgService;
import org.changchen.fgt.utils.Xml2JsonUtil;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;

@Service
public class LiveEpgServiceImpl implements LiveEpgService{
	
	
	private static final String EPG_FILE_URL = "https://epg.112114.xyz/pp.xml";
	
	
	private static final String EPG_DIR = "epg";
	
	
	/**   
	 * @Fields EPG_FILE_SIZE_MAX: 直播节目表文件大小上限   
	 */
	private static final Integer EPG_FILE_SIZE_MAX = 50;
	
	
	private Map<String, Map<String, List<LiveEpgDto>>> EPG_MAP = new HashMap<>();
	
	
	@Override
	public List<LiveEpgDto> getEpgList(String channel){
		
		if(StringUtils.isBlank(channel)) {
			return Collections.emptyList();
		}
		
		// 当前日期
		String today = DateUtil.format(new Date(), "yyyyMMdd");
				
		try {
			this.init(today);
		} catch (Exception e) {
			e.printStackTrace();
			return Collections.emptyList();
		}
	
		Map<String, List<LiveEpgDto>> todayEpg = EPG_MAP.get(today);
		if(todayEpg == null) {
			return Collections.emptyList();
		}
		
		List<LiveEpgDto> epgList = todayEpg.get(channel.toUpperCase());
		
		if(CollectionUtil.isEmpty(epgList)) {
			return Collections.emptyList();
		}
		
		String currentTime = DateUtil.format(new Date(), "HHmmss");
		epgList.forEach(item -> {
			Integer start = Integer.valueOf(item.getStart().replaceAll(":", ""));
			Integer stop = Integer.valueOf(item.getStop().replaceAll(":", ""));
			Integer current = Integer.valueOf(currentTime);
			item.setCurrent(current >= start && current <= stop);
		});
		
		return epgList;
	}
	
	
	
	private void init(String today) throws IORuntimeException, URISyntaxException, IOException {
		
		// 当前日期
		Map<String, List<LiveEpgDto>> todayEpg = EPG_MAP.get(today);
		
		if(todayEpg != null){
			return;
		}
		
		// 没有则读取文件
		String parentPath = this.getParentDir();
		String parentDir = parentPath + File.separator + EPG_DIR;
		File epgFile = new File(parentDir + File.separator + today + ".xml");
		if(!epgFile.exists()) {
			
			// 创建文件夹
			File parentFile = new File(parentDir);
			if(!parentFile.exists()) {
				parentFile.mkdir();
			}
			
			// 下载文件
			FileOutputStream fos = new FileOutputStream(epgFile);
			
			WebClient webClient =WebClient.builder()
	                //修改maxInMemorySize的缓存值，默认是256k。修改为10MB
	                .codecs(item->item.defaultCodecs().maxInMemorySize(EPG_FILE_SIZE_MAX * 1024 * 1024))
	                .build();
			
			Resource resource = webClient.get().uri(EPG_FILE_URL)
					.accept(MediaType.APPLICATION_OCTET_STREAM).exchange()
					.block().bodyToMono(Resource.class).block();
			IoUtil.copy(resource.getInputStream(), fos);
		}
		
		// 读取文件
		String xml = IoUtil.read(new FileInputStream(epgFile), Charset.forName("UTF-8"));
		if(StringUtils.isBlank(xml)) {
			return;
		}
		
		// 解析XML
		JSONObject json =  Xml2JsonUtil.xml2JSON(xml);
		JSONArray programmes = json.getJSONArray("programme");
		
		List<LiveEpgDto> allEpg = new ArrayList<>();
		for(Object obj : programmes) {
			JSONObject jsonObj = (JSONObject)obj;
			String channel = jsonObj.getString("@channel");
			Date startDate = DateUtil.parse(jsonObj.getString("@start"), "yyyyMMddHHmmss +0800");
			String start = DateUtil.format(startDate, "HH:mm:ss");
			Date stopDate = DateUtil.parse(jsonObj.getString("@stop"), "yyyyMMddHHmmss +0800");
			String stop = DateUtil.format(stopDate, "HH:mm:ss");
			String content = jsonObj.getJSONObject("title").getString("#text");
			
			LiveEpgDto epgDto = LiveEpgDto.builder().channel(channel.toUpperCase()).start(start).stop(stop).content(content).build();
			allEpg.add(epgDto);		
		}
		
		todayEpg = allEpg.stream().collect(Collectors.groupingBy(LiveEpgDto::getChannel, Collectors.toList()));
		EPG_MAP.put(today, todayEpg);
	}
	
	
	
	/**   
	 * @Title:      getParentDir   
	 * @Description:获取Jar包的目录   
	 * @param:      @return      
	 * @return:     String      
	 * @throws   
	 */
	private String getParentDir() {
		// 获取 jar 所在目录
		ApplicationHome home = new ApplicationHome(this.getClass());
		File jarFile = home.getSource();
		return jarFile.getParentFile().toString();
	}
	

}
